<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <FeatherIcon name="chevron-left" size="24" color="#333" />
      </view>
      <view class="title">草稿箱</view>
      <view class="right-placeholder"></view>
    </view>

    <!-- 本地存储提示 -->
    <view class="storage-tip">
      <view class="tip-icon">
        <FeatherIcon name="alert-circle" size="16" color="#ff9800" />
      </view>
      <text class="tip-text"
        >草稿仅保存在本地<br />清除应用数据或更换设备将丢失，建议及时发布</text
      >
    </view>

    <!-- 草稿列表 -->
    <scroll-view
      scroll-y
      class="drafts-list"
      :style="{ height: scrollHeight + 'px' }"
      enable-flex
    >
      <view v-if="drafts.length === 0" class="empty-state">
        <text>暂无草稿</text>
      </view>

      <view v-else class="draft-items">
        <view
          v-for="draft in drafts"
          :key="draft.id"
          class="draft-item"
          @click="editDraft(draft)"
        >
          <view class="draft-content">
            <text class="draft-title">{{ draft.title || "无标题" }}</text>
            <text class="draft-preview">{{ getPreview(draft.content) }}</text>
            <view class="draft-info">
              <text class="draft-time">{{ formatTime(draft.updateTime) }}</text>
              <view class="draft-actions">
                <button
                  class="action-btn delete-btn"
                  @click.stop="confirmDelete(draft)"
                >
                  <FeatherIcon name="trash-2" size="16" color="#ff4d4f" />
                  <text>删除</text>
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import FeatherIcon from "@/components/FeatherIcon.vue";
import { showSuccess, showError } from "@/utils/common";

// 草稿列表
const drafts = ref([]);
// 滚动区域高度
const scrollHeight = ref(0);

// 计算滚动区域高度
const calculateScrollHeight = () => {
  const systemInfo = uni.getSystemInfoSync();
  const windowHeight = systemInfo.windowHeight;
  // 减去顶部导航栏高度(90rpx)和提示栏高度(88rpx)，转换rpx为px
  const headerHeight = uni.upx2px(90 + 88);
  scrollHeight.value = windowHeight - headerHeight;
};

// 加载草稿
const loadDrafts = () => {
  try {
    const savedDrafts = uni.getStorageSync("article_drafts") || [];
    drafts.value = savedDrafts;
  } catch (error) {
    console.error("加载草稿失败:", error);
    showError("加载草稿失败");
  }
};

// 编辑草稿
const editDraft = (draft) => {
  uni.navigateTo({
    url: `/pages/article/post?draftId=${draft.id}`,
  });
};

// 删除草稿
const deleteDraft = (draft) => {
  try {
    const savedDrafts = uni.getStorageSync("article_drafts") || [];
    const newDrafts = savedDrafts.filter((d) => d.id !== draft.id);
    uni.setStorageSync("article_drafts", newDrafts);
    drafts.value = newDrafts;
    showSuccess("删除成功");
  } catch (error) {
    console.error("删除草稿失败:", error);
    showError("删除失败");
  }
};

// 确认删除
const confirmDelete = (draft) => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这篇草稿吗？",
    success: (res) => {
      if (res.confirm) {
        deleteDraft(draft);
      }
    },
  });
};

// 获取预览内容
const getPreview = (content) => {
  if (!content) return "无内容";
  // 移除 Markdown 语法和 HTML 标签
  const plainText = content
    .replace(/!\[.*?\]\(.*?\)/g, "[图片]") // 替换图片
    .replace(/\[.*?\]\(.*?\)/g, "") // 移除链接
    .replace(/#+\s/g, "") // 移除标题标记
    .replace(/\*\*(.*?)\*\*/g, "$1") // 移除加粗
    .replace(/\*(.*?)\*/g, "$1") // 移除斜体
    .replace(/<[^>]+>/g, ""); // 移除HTML标签
  return plainText.slice(0, 100) + (plainText.length > 100 ? "..." : "");
};

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now - date;

  // 今天之内
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return `今天 ${hours}:${minutes}`;
  }

  // 昨天
  if (diff < 48 * 60 * 60 * 1000) {
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return `昨天 ${hours}:${minutes}`;
  }

  // 其他时间
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

onMounted(() => {
  loadDrafts();
  calculateScrollHeight();

  // 监听窗口大小变化
  uni.onWindowResize(() => {
    calculateScrollHeight();
  });
});
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f5f6f7;
  display: flex;
  flex-direction: column;
}

.header {
  padding: 20rpx 30rpx;
  padding-top: 60rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #eeeeee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 90rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.right-placeholder {
  width: 60rpx;
}

.storage-tip {
  display: flex;
  align-items: center;
  padding: 16rpx 30rpx;
  background-color: #fff8e1;
  border-bottom: 1rpx solid #ffe0b2;

  .tip-icon {
    margin-right: 12rpx;
    display: flex;
    align-items: center;
  }

  .tip-text {
    font-size: 24rpx;
    color: #ff9800;
    flex: 1;
    line-height: 1.4;
  }
}

.drafts-list {
  flex: 1;
  padding: 20rpx;
  box-sizing: border-box;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  color: #999;
  font-size: 28rpx;
}

.draft-items {
  padding-bottom: 40rpx;
}

.draft-item {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  &:last-child {
    margin-bottom: 0;
  }
}

.draft-content {
  padding: 20rpx;
  word-break: break-all;
}

.draft-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 12rpx;
  display: block;
  word-wrap: break-word;
}

.draft-preview {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 16rpx;
  display: block;
  word-wrap: break-word;
}

.draft-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16rpx;
  padding-top: 16rpx;
  border-top: 1px solid #f5f5f5;
}

.draft-time {
  font-size: 24rpx;
  color: #999;
}

.draft-actions {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  margin: 0;
  padding: 0;
  background: none;
  border: none;
  outline: none;

  &.delete-btn {
    display: flex;
    align-items: center;
    gap: 4rpx;
    padding: 8rpx 16rpx;
    border-radius: 6rpx;
    transition: all 0.3s ease;

    text {
      font-size: 24rpx;
      color: #ff4d4f;
      margin-left: 4rpx;
    }

    &:active {
      background-color: #fff1f0;
    }
  }

  &::after {
    border: none;
  }
}
</style>
